package com.yc.zyz.util;

import com.google.gson.Gson;
import com.yc.mybatis.damai.MyBatisHelper;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Company 源辰信息
 *
 * @author navy
 * @date 2024/7/28
 * Email haijunzhou@hnit.edu.cn
 */
public class Utils {

    public static void print(HttpServletResponse resp, Object object) throws IOException {
        Gson gson = new Gson();
        String json = gson.toJson(object);
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().println(json);
    }

    // 模板模式,执行sql方法
    public static Object exec(java.util.function.Function<SqlSession,Object> handler){
        SqlSession session = MyBatisHelper.getSession();
        Object ret = null;
        try{
            // handler 业务代码处理器
            ret = handler.apply(session);
            session.commit();
            return ret;
        } catch (RuntimeException e ){
            session.rollback();
            throw e;
        } finally {
            session.close();
        }
    }

}
